import {BridgeHostEvents, Completer, IRpcBridgeHost} from "../src/Core/RpBridge";

/**
 Created by:
 muhtearjan mehmood مۇختەرجان مەخمۇت (Email: yeganaaa@163.com)
 At 8/9/20 11:13 PM
 */

export class MemoryRpcBridgeHost implements IRpcBridgeHost<void> {
    backend: void;
    // isOpen: boolean = false
    private otherSide: MemoryRpcBridgeHost = null!
    private eventHandler: BridgeHostEvents = null!
    private ensurePrepared = Completer.create<void>()

    constructor() {
    }

    async close(): Promise<void> {
        // if (!this.isOpen) return
        await this.ensurePrepared.promise
        // this.isOpen = false
        await this.eventHandler.onClose()
        this.otherSide.eventHandler.onClose()
    }

    async open(): Promise<void> {
        // if (!this.isOpen) {
            await this.ensurePrepared.promise
            // this.isOpen = true
            await this.eventHandler.onReady()
        // }
    }

    async prepare(eventHandler: BridgeHostEvents): Promise<void> {
        this.eventHandler = eventHandler
        this.ensurePrepared.complete()
    }

    async send(data: Uint8Array): Promise<void> {
        await this.ensurePrepared.promise
        await this.otherSide.ensurePrepared.promise
        // try {
        this.otherSide.eventHandler.onMessage(data)
        // }
        // catch (e) {
        //     await this.eventHandler.onError(e)
        //     await this.eventHandler.onClose()
        // }
    }

    public createLinkedBridge(): MemoryRpcBridgeHost {
        if (this.otherSide != null) throw new Error("This bridge already linked to other bridge.")
        this.otherSide = new MemoryRpcBridgeHost()
        this.otherSide.otherSide = this
        return this.otherSide
    }
}